package animation;

import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AnotationParser {
	private static final String PACKAGETOSCAN = "service";

	private static Map<String, AnotationBean> actionMap = new HashMap<String, AnotationBean>();

	public static Map<String, AnotationBean> strutsAnotation() {
		List<String> classes = new ArrayList<String>();
		getClasses(classes, null);
		parseAction(classes);
		return actionMap;
	}

	private static void getClasses(List<String> classes, String packs) {
		String classpath = Thread.currentThread().getContextClassLoader()
				.getResource("").getPath();
		String[] packages = null;
		if (packs != null) {
			packages = packs.split(",");
		} else {
			packages = PACKAGETOSCAN.split(",");
		}
		for (String pack : packages) {
			File file = new File(classpath + pack.replace(".", "/"));
			File[] files = file.listFiles();
			for (File f : files) {
				String fname = f.getName().substring(0,
						f.getName().lastIndexOf("."));
				if (!f.isDirectory()) {
					synchronized (classes) {
						classes.add(pack + "." + fname);
					}
				} else {
					getClasses(classes, pack + "." + fname);
				}
			}
		}
	}

	@SuppressWarnings("rawtypes")
	private static void parseAction(List<String> classes) {
		for (String clazzStr : classes) {
			try {
				Class clazz = Class.forName(clazzStr);
				for (Method m : clazz.getMethods()) {
					ActionsAnotation c = m
							.getAnnotation(ActionsAnotation.class);
					if (c != null) {
						AnotationBean a = new AnotationBean();
						a.setPath(c.path());
						// a.setMethod(m.getName());
						a.setActionClass(c.actionClass());
						a.setActionType(clazzStr);
						a.setFormClass(c.formClasss());

						Map<String, String> actionForward = new HashMap();
						ActionAnotation[] mapurl = c.mapurl();
						for (int i = 0; i < mapurl.length; i++) {
							actionForward.put(mapurl[i].name(),
									mapurl[i].value());
						}
						a.setActionForward(actionForward);
						actionMap.put(c.path(), a);
					}
				}
			} catch (Exception e) {

				e.printStackTrace();
			}
		}
	}
}
